package com.qing.collector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 质数的性能测试
 */
public class Demo2 {


	public static void main(String[] args) {
		int n=10_000_000;
		Long startTime=System.currentTimeMillis();
		IntStream.rangeClosed(2,n).boxed().collect(new PrimeNumbersCollector());
		System.out.println(System.currentTimeMillis()-startTime);  //7441

		Long startTime2=System.currentTimeMillis();
		IntStream.rangeClosed(2,n).boxed().collect(Collectors.groupingBy(candidate->isPrime(candidate)));
		System.out.println(System.currentTimeMillis()-startTime2); //	13058

		Long startTime3=System.currentTimeMillis();
		IntStream.rangeClosed(2,n).boxed().collect(()->new HashMap<Boolean,List<Integer>>(){{
					put(true,new ArrayList<>());
					put(false,new ArrayList<>()); //供应源
				}},
				(acc,candidate)->{
					acc.get(PrimeNumbersCollector.isPrime(acc.get(true),candidate)).add(candidate); //累加器
				},
				(map1,map2)->{
					map1.get(true).addAll(map2.get(true));
					map1.get(false).addAll(map2.get(false));
				}
				);
		System.out.println(System.currentTimeMillis()-startTime3); //	7821

	}

	public static boolean isPrime(int candidate){
		int candidateRoot=(int)Math.sqrt((double) candidate);
		return IntStream.rangeClosed(2,candidateRoot).noneMatch(i->candidate%i==0);
	}

}
